package cn.tedu.fresheveryday.controller;

import cn.tedu.fresheveryday.exception.ServiceException;
import cn.tedu.fresheveryday.pojo.dto.UserReceiveInfoDTO;
import cn.tedu.fresheveryday.pojo.entity.User;
import cn.tedu.fresheveryday.pojo.entity.UserReceiveInfo;
import cn.tedu.fresheveryday.restful.JsonResult;
import cn.tedu.fresheveryday.restful.ResponseCode;
import cn.tedu.fresheveryday.service.IReceiveInfoService;
import cn.tedu.fresheveryday.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Api(tags = "收货信息模块")
@RequestMapping(path = "/receive_info", produces = "application/json;charset=utf-8")
public class UserReceiveInfoController {
    Logger logger = LoggerFactory.getLogger(UserReceiveInfoController.class);
    @Autowired
    private IReceiveInfoService service;

    /**
     * 查询用户的收货信息
     *
     * @return
     */
    @ApiOperation("查询用户的收货信息")
    @GetMapping("/selectByUserId")
    public List<UserReceiveInfo> selectByUserId(HttpSession session) {
        User user = (User) session.getAttribute("user");

        if (user != null) {
            return service.selectByUserId(user.getId());
        }

        return null;
    }

    /**
     * 通过id修改收货信息
     * @param rec
     * @return
     */
    @PostMapping("/updateById")
    @ApiOperation("修改用户的收货信息")
    public JsonResult<Void> updateById(@RequestBody UserReceiveInfo rec) {
        service.updateById(rec);

        return JsonResult.success("修改成功", null);
    }

    /**
     * 添加收货信息
     * @param userReceiveInfoDTO
     * @return
     */
    @PostMapping("/insert")
    @ApiOperation("添加收货信息")
    public JsonResult<Void> insert(@RequestBody UserReceiveInfoDTO userReceiveInfoDTO, HttpSession session) {
        // 获取登录的用户信息
        logger.debug(userReceiveInfoDTO+"-------------");
        User user = (User) session.getAttribute("user");

        if (user == null) {
            throw new ServiceException(ResponseCode.BAD_REQUEST, "添加失败，请先登录。");
        }

        UserReceiveInfo userReceiveInfo = new UserReceiveInfo();

        userReceiveInfo.setId(StringUtils.uuid()); // 设置id
        userReceiveInfo.setUserId(user.getId()); // 设置用户id
        BeanUtils.copyProperties(userReceiveInfoDTO, userReceiveInfo);

        service.insert(userReceiveInfo);

        return JsonResult.success("添加成功", null);
    }

}